#include "multhread.h"
#include "sniffer.h"
#include "ui_sniffer.h"

#include <QFile>


Sniffer::Sniffer(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Sniffer)
{
    ui->setupUi(this);

    statusBar()->showMessage("welcome to sniffer");
    ui->toolBar->addAction(ui->actionrun);
    ui->toolBar->addAction(ui->actionempty);
    countNumber= 0;
    showNetworkCards();
    showProtocols();
    multhread* thread = new multhread;
    static bool index = false;
    fi = false;
    filt = new Filter;
    connect(ui->comboBox, &QComboBox::currentIndexChanged, this, &Sniffer::on_comboBox_currentIndexChanged);
    connect(ui->tableWidget,&QTableWidget::cellClicked,this,&Sniffer::on_tableWidget_cellClicked);
    connect(ui->comboBox_2, &QComboBox::currentIndexChanged, this, &Sniffer::on_comboBox_2_currentIndexChanged);

    connect(ui->actionrun, &QAction::triggered, this, [=]() {
        index = !index; // 切换index状态
        if (index)
        {
            // 启动数据获取前禁用搜索框
            ui->lineEdit_srcIP->setEnabled(false);
            ui->lineEdit_dstIP->setEnabled(false);




            ui->tableWidget->clearContents(); // 清空表格内容
            ui->tableWidget->setRowCount(0); // 设置表格行数为0
            countNumber = 0; // 重置计数器
            numberRow = -1; // 重置行号
            filt->quit(); // 停止过滤器线程
            int dataSize = this->pData.size(); // 获取数据包数量
            for (int i = 0; i < dataSize; i++)
            {
                free((char*)(this->pData[i].pkt_content)); // 释放数据包内容内存
                this->pData[i].pkt_content = nullptr; // 将数据包内容指针置空
            }
            QVector<DataPackage>().swap(pData); // 清空数据包向量

            int ret = capture(); // 捕获数据包
            if (ret != -1 && pointer) // 如果捕获成功且指针有效
            {
                if (fi == true)
                {
                    fi = false; // 重置过滤标志
                }
                thread->setPointer(pointer); // 设置pcap指针
                thread->setFlag(); // 设置线程标志
                thread->start(); // 启动线程

                ui->actionrun->setIcon(QIcon(":/qrc/images/stop.png")); // 设置停止图标
                ui->comboBox->setEnabled(false); // 禁用组合框
                ui->comboBox_2->setEnabled(false); // 禁用组合框2
                ui->comboBox_2->setCurrentIndex(0); // 重置组合框2索引


            }
            else
            {
                index = !index; // 捕获失败，切换index状态
            }
        }
        else
        {
            // 启动数据获取前禁用搜索框
            ui->lineEdit_srcIP->setEnabled(false);
            ui->lineEdit_dstIP->setEnabled(false);



            thread->resetFlag(); // 重置线程标志
            thread->quit(); // 停止线程
            thread->wait(); // 等待线程结束
            ui->actionrun->setIcon(QIcon(":/qrc/images/start.png")); // 设置启动图标
            ui->comboBox->setEnabled(true); // 启用组合框
            ui->comboBox_2->setEnabled(true); // 启用组合框2
            pcap_close(pointer); // 关闭pcap指针
            pointer = nullptr; // 将指针置空
        }

        // 启动数据获取后启用搜索框
        ui->lineEdit_srcIP->setEnabled(true);
        ui->lineEdit_dstIP->setEnabled(true);


    });
    connect(ui->actionempty, &QAction::triggered, this, [=]() {
        ui->tableWidget->clearContents();
        ui->tableWidget->setRowCount(0);
        ui->treeWidget->clear();
        countNumber = 0;
        numberRow = -1;
    });
    connect(thread,&multhread::send, this, &Sniffer::HandleMessage);
    connect(filt, &Filter::send, this, &Sniffer::HandlePair);
    // 连接搜索框的信号到槽函数
    connect(ui->lineEdit_srcIP, &QLineEdit::textChanged, this, &Sniffer::on_searchSrcIP_textChanged);
    connect(ui->lineEdit_dstIP, &QLineEdit::textChanged, this, &Sniffer::on_searchDstIP_textChanged);

    // 设置搜索框初始为禁用，直到数据获取完成
    ui->lineEdit_srcIP->setEnabled(false);
    ui->lineEdit_dstIP->setEnabled(false);


    ui->toolBar->setMovable(false);
    ui->tableWidget->setColumnCount(7);
    ui->tableWidget->verticalHeader()->setDefaultSectionSize(30);
    QStringList title = { "NO","Time","Source","Destination","Protocal","Length","Info" };
    ui->tableWidget->setHorizontalHeaderLabels(title);

    ui->tableWidget->setColumnWidth(0, 50);
    ui->tableWidget->setColumnWidth(1, 100);
    ui->tableWidget->setColumnWidth(2, 300);
    ui->tableWidget->setColumnWidth(3, 300);
    ui->tableWidget->setColumnWidth(4, 100);
    ui->tableWidget->setColumnWidth(5, 100);
    ui->tableWidget->setColumnWidth(6, 700);

    ui->tableWidget->setShowGrid(true);
    ui->tableWidget->verticalHeader()->setVisible(false);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->treeWidget->setHeaderHidden(true);

    this->centralWidget()->setLayout(ui->verticalLayout);
    //隐藏菜单栏
    this->setMenuBar(nullptr);
    ui->tableWidget->setStyleSheet("QTableView::item:selected{background-color: #6a6ea9; color: white;}");

    loadStyle(":/qrc/qss/lightblue.css");
}
void Sniffer::loadStyle(const QString &qssFile)
{
    //开启计时
    QElapsedTimer time;
    time.start();

    //加载样式表
    QString qss;
    QFile file(qssFile);
    if (file.open(QFile::ReadOnly)) {
        //用QTextStream读取样式文件不用区分文件编码 带bom也行
        QStringList list;
        QTextStream in(&file);
        //in.setCodec("utf-8");
        while (!in.atEnd()) {
            QString line;
            in >> line;
            list << line;
        }

        file.close();
        qss = list.join("\n");
        QString paletteColor = qss.mid(20, 7);
        qApp->setPalette(QPalette(paletteColor));
        //用时主要在下面这句
        qApp->setStyleSheet(qss);
    }

    qDebug() << "用时:" << time.elapsed();
}
Sniffer::~Sniffer()
{
    // 释放 pData 中的 pkt_content
    for (auto &data : pData)
    {
        if (data.pkt_content)
        {
            free((char*)(data.pkt_content));
            data.pkt_content = nullptr;
        }
    }
    pData.clear();

    // 删除动态分配的对象
    delete filt;
    delete ui;

    // 关闭 pcap 指针如果尚未关闭
    if (pointer)
    {
        pcap_close(pointer);
        pointer = nullptr;
    }
}

void Sniffer::showNetworkCards()
{
    // int i = 0;

    /* 获取本地网卡信息 */
    if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
    {
        ui->comboBox->addItem("error:" + QString(errbuf));
    }
    else
    {
        ui->comboBox->clear();
        ui->comboBox->addItem("选择网卡设备!");
        for (device = alldevs; device != nullptr; device = device->next)
        {
            /*
            QString device_name = device->name;
            device_name.replace("rpcap://\\Device\\","");
            QString device_des = device->description;
            device_des.replace("Network adapter", "");
            device_des.replace("on local host", "");
            QString item = device_name + device_des;
            */
            ui->comboBox->addItem(device->description);
        }
    }
}

void Sniffer::showProtocols()
{
    QStringList Protocols = { "选择协议类型","ARP","TCP","UDP","ICMP","DNS" };
    for (int i = 0; i < Protocols.length(); i++)
    {
        ui->comboBox_2->addItem(Protocols[i]);
    }
}

int Sniffer::capture()
{
    if (device) // 检查设备是否存在
    {
        // 打开设备进行数据包捕获
        pointer = pcap_open(device->name, MAXDATAFRAMES, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf);
    }
    else
    {
        return -1; // 如果设备不存在，返回-1
    }
    if (!pointer) // 检查指针是否为空
    {
        pcap_freealldevs(alldevs); // 释放所有设备
        device = nullptr; // 将设备指针置为空
        return -1; // 返回-1表示失败
    }
    else
    {
        if (pcap_datalink(pointer) != DLT_EN10MB) return false; // 必须是以太网协议
        statusBar()->showMessage(device->description); // 在状态栏显示设备描述
        return pointer != nullptr; // 返回指针是否为空
    }
}

void Sniffer::on_comboBox_currentIndexChanged(int index)
{
    int i = 0;
    if (index != 0)
    {
        for (device = alldevs; i < index - 1; device = device->next ,i++);
    }
    return;
}


void Sniffer::on_comboBox_2_currentIndexChanged(int pro)
{
    if (pro != 0) // 0 对应 "选择协议类型"
    {
        ui->tableWidget->clearContents();
        ui->tableWidget->setRowCount(0);
        countNumber = 0;
        numberRow = -1;
        filt->quit();
        QVector<DataPackage>* pdata = &pData;
        if (fi == false)
        {
            filt->setPackages(pdata);
            fi = true;
        }
        select.clear();
        QString protocol;
        switch (pro)
        {
            case 1: protocol = "ARP"; break;
            case 2: protocol = "TCP"; break;
            case 3: protocol = "UDP"; break;
            case 4: protocol = "ICMP"; break;
            case 5: protocol = "DNS"; break;
            default: protocol = ""; break;
        }
        filt->setProtocol(protocol);
        filt->run();
    }
}

void Sniffer::HandleMessage(DataPackage data)
{
        if (fi == false)
        this->pData.push_back(data);


    QString type = data.getPackageType();
    QColor color;
    if (type == "TCP")
        color = QColor(231, 230, 255);
    else if (type == "UDP")
        color = QColor(218, 238, 255);
    else if (type == "ARP")
        color = QColor(250, 240, 215);
    else if (type == "ICMP")
        color = QColor(252, 224, 255);
    else if (type == "DNS")
        color = QColor(218, 238, 255);

    // 检查当前数据是否符合过滤条件
    bool matchSrc = true;
    bool matchDst = true;

    if (!filterSrcIP.isEmpty())
    {
        matchSrc = data.getSource().contains(filterSrcIP);
    }

    if (!filterDstIP.isEmpty())
    {
        matchDst = data.getDestination().contains(filterDstIP);
    }

    if (matchSrc && matchDst)
    {
        showData.append(data);

        // 更新表格显示
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);

        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1)));
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(data.getTimeStmp()));
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem(data.getSource()));
        ui->tableWidget->setItem(row, 3, new QTableWidgetItem(data.getDestination()));
        ui->tableWidget->setItem(row, 4, new QTableWidgetItem(data.getPackageType()));
        ui->tableWidget->setItem(row, 5, new QTableWidgetItem(data.getDataLength()));
        ui->tableWidget->setItem(row, 6, new QTableWidgetItem(data.getInfo()));
        for (int i = 0; i < 7; i++)
        {
            ui->tableWidget->item(countNumber, i)->setBackground(QBrush(color));
        }
    }

    countNumber++;
    // ui->tableWidget->insertRow(countNumber);
    // if (fi == false)
    //     this->pData.push_back(data);
    // QString type = data.getPackageType();
    // QColor color;
    // if (type == "TCP")
    //     color = QColor(231, 230, 255);
    // else if (type == "UDP")
    //     color = QColor(218, 238, 255);
    // else if (type == "ARP")
    //     color = QColor(250, 240, 215);
    // else if (type == "ICMP")
    //     color = QColor(252, 224, 255);
    // else if (type == "DNS")
    //     color = QColor(218, 238, 255);

    // ui->tableWidget->setItem(countNumber, 0, new QTableWidgetItem(QString::number(countNumber + 1)));
    // ui->tableWidget->setItem(countNumber, 1, new QTableWidgetItem(data.getTimeStmp()));
    // ui->tableWidget->setItem(countNumber, 2, new QTableWidgetItem(data.getSource()));
    // ui->tableWidget->setItem(countNumber, 3, new QTableWidgetItem(data.getDestination()));
    // ui->tableWidget->setItem(countNumber, 4, new QTableWidgetItem(data.getPackageType()));
    // ui->tableWidget->setItem(countNumber, 5, new QTableWidgetItem(data.getDataLength()));
    // ui->tableWidget->setItem(countNumber, 6, new QTableWidgetItem(data.getInfo()));
    // for (int i = 0; i < 7; i++)
    // {
    //     ui->tableWidget->item(countNumber, i)->setBackground(QBrush(color));
    // }
    // countNumber++;
}

void Sniffer::HandlePair(std::pair<int, int> selected)
{
    select.insert(selected);
    HandleMessage(pData[select[selected.first]]);
}



// void Sniffer::on_tableWidget_cellClicked(int row, int column)
// {
//     // 如果点击的行是当前选中的行或行号小于0，直接返回
//     if (row == numberRow || row < 0)
//     {
//         return;
//     }
//     else
//     {
//         // 如果fi标志为真，根据选择的行重新设置行号
//         if(fi == true)
//         {
//             row = select[row];
//         }
//         // 清除表格内容
//         ui->treeWidget->clear();
//         // 更新当前行号
//         numberRow = row;
//         // 如果行号小于0，直接返回
//         if(numberRow < 0)
//         {
//             return;
//         }
//         // 获取目标MAC地址
//         QString desMac = pData[row].getDesMacAddr();
//         // 获取源MAC地址
//         QString srcMac = pData[row].getSrcMacAddr();
//         // 获取MAC类型
//         QString macType = pData[row].getMacType();
//         // 构建以太网协议的树节点描述
//         QString tree = "Ethernet  -  Src:" + srcMac + "  -   Des:" + desMac;
//         // 创建新的树节点并添加到树控件中
//         QTreeWidgetItem* item = new QTreeWidgetItem(QStringList()<<tree);
//         ui->treeWidget->addTopLevelItem(item);
//         // 添加源MAC地址、目标MAC地址和类型作为子节点
//         item->addChild(new QTreeWidgetItem(QStringList()<<"Source:"+srcMac));
//         item->addChild(new QTreeWidgetItem(QStringList()<<"Destination:"+desMac));
//         item->addChild(new QTreeWidgetItem(QStringList()<<"Type:"+macType));
        
//         // 如果MAC类型为IPv4
//         if(macType == "IPv4(0x0800)")
//         {
//             // 获取源IP地址和目标IP地址
//             QString srcIp = pData[row].getSrcIpAddr();
//             QString desIp = pData[row].getDesIpAddr();
//             // 构建IPv4协议的树节点描述
//             tree = "Internet Protocol Version 4  -   Src:"+srcIp+"  -   Des:"+desIp;
//             // 创建新的IPv4树节点并添加到树控件中
//             QTreeWidgetItem* item = new QTreeWidgetItem(QStringList()<<tree);
//             ui->treeWidget->addTopLevelItem(item);
//             // 获取IP协议类型
//             QString ipProtocol = pData[row].getIpProtocol();
//             // 添加IP信息作为子节点
//             QList<QTreeWidgetItem *> ipItems = pData[numberRow].getIp();
//             for(auto &childIpItem : ipItems) {
//                 item->addChild(childIpItem);
//             }

//             // 根据IP协议类型处理不同的协议
//             if (ipProtocol == "TCP(6)")
//             {
//                 // 获取TCP源端口和目标端口
//                 QString sPort = pData[numberRow].getTcpSrcPort();
//                 QString dPort = pData[numberRow].getTcpDesPort();
//                 // 构建TCP协议的树节点描述
//                 tree = "Transmission Control Protocol  -   Src Port: " + sPort + "  -   Dst Port: " + dPort;
//                 // 创建新的TCP树节点并添加到树控件中
//                 QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << tree);
//                 ui->treeWidget->addTopLevelItem(item);
//                 // 获取TCP序列号和确认号
//                 QString seqNum = pData[numberRow].getTcpSeq();
//                 QString ackNum = pData[numberRow].getTcpAck();
//                 // 添加TCP端口和序列号、确认号作为子节点
//                 item->addChild(new QTreeWidgetItem(QStringList() << "Source Port: " + sPort));
//                 item->addChild(new QTreeWidgetItem(QStringList() << "Destination Port: " + dPort));
//                 item->addChild(new QTreeWidgetItem(QStringList() << seqNum));
//                 item->addChild(new QTreeWidgetItem(QStringList() << ackNum));
//             }
//             else if (ipProtocol == "UDP(17)")
//             {
//                 // 获取UDP源端口、目标端口和长度
//                 QString sPort = pData[numberRow].getUdpSrcPort();
//                 QString dPort = pData[numberRow].getUdpDesPort();
//                 QString length = pData[numberRow].getUdpLength();
//                 // 构建UDP协议的树节点描述
//                 tree = "User Datagram Protocol  -   Src Port: " + sPort + "  -   Dst Port: " + dPort;
//                 // 创建新的UDP树节点并添加到树控件中
//                 QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << tree);
//                 ui->treeWidget->addTopLevelItem(item);
//                 // 添加UDP端口和长度作为子节点
//                 item->addChild(new QTreeWidgetItem(QStringList() << "Source Port: " + sPort));
//                 item->addChild(new QTreeWidgetItem(QStringList() << "Destination Port: " + dPort));
//                 item->addChild(new QTreeWidgetItem(QStringList() << "Length: " + length));
                
//                 // 如果源端口或目标端口为53，表示DNS协议
//                 if (sPort == "53" || dPort == "53")
//                 {
//                     // 获取DNS标志
//                     QString qr = pData[numberRow].getDnsFlagsQR();
//                     // 构建DNS协议的树节点描述
//                     tree = "Domain Name System";
//                     if (qr == "0 Message is a query")
//                         tree += " (query)";
//                     else if (qr == "1 Message is a response")
//                         tree += " (response)";
//                     // 创建新的DNS树节点并添加到树控件中
//                     QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << tree);
//                     ui->treeWidget->addTopLevelItem(item);
//                     // 添加DNS信息作为子节点
//                     item->addChildren(pData[numberRow].getDns());
//                 }
//             }
//             else if (ipProtocol == "ICMP(1)")
// 			{
// 				// 构建ICMP协议的树节点描述
// 				tree = "Internet Control Message Protocol";
//                 // 创建新的ICMP树节点并添加到树控件中
//                 QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << tree);
//                 ui->treeWidget->addTopLevelItem(item);
//                 // 添加ICMP信息作为子节点
//                 item->addChildren(pData[numberRow].getIcmp());
// 			}
//         }
//         // 如果MAC类型为ARP
//         else if (macType == "ARP(0x0806)")
// 		{
// 			// 获取ARP操作类型
// 			QString Op = pData[numberRow].getArpOp();
// 			// 根据ARP操作类型构建树节点描述
// 			if (Op == "request(1)")
// 			{
// 				tree = "Address Resolution Protocol (request)";
// 			}
// 			else if (Op == "reply(2)")
// 			{
// 				tree = "Address Resolution Protocol (reply)";
// 			}
// 			else
// 			{
// 				tree = "Address Resolution Protocol";
// 			}
// 			// 创建新的ARP树节点并添加到树控件中
// 			QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << tree);
// 			ui->treeWidget->addTopLevelItem(item);
// 			// 添加ARP信息作为子节点
// 			item->addChildren(pData[numberRow].getArp());
// 		}
//     }
// }
void Sniffer::on_tableWidget_cellClicked(int row, int column)
{
    // 清除之前的树视图内容
    ui->treeWidget->clear();

    // 检查行号是否有效
    if (row < 0 || row >= showData.size())
    {
        return;
    }

    // 更新当前行号
    numberRow = row;

    // 获取当前数据显示
    DataPackage &data = showData[row];

    // 获取目标MAC地址、源MAC地址和MAC类型
    QString desMac = data.getDesMacAddr();
    QString srcMac = data.getSrcMacAddr();
    QString macType = data.getMacType();

    // 构建以太网协议的树节点描述
    QString tree = "Ethernet  -  Src:" + srcMac + "  -   Des:" + desMac;
    QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << tree);
    ui->treeWidget->addTopLevelItem(item);

    // 添加源MAC地址、目标MAC地址和类型作为子节点
    item->addChild(new QTreeWidgetItem(QStringList() << "Source: " + srcMac));
    item->addChild(new QTreeWidgetItem(QStringList() << "Destination: " + desMac));
    item->addChild(new QTreeWidgetItem(QStringList() << "Type: " + macType));

    // 根据MAC类型进一步解析
    if (macType == "IPv4(0x0800)")
    {
        QString srcIp = data.getSrcIpAddr();
        QString desIp = data.getDesIpAddr();
        tree = "Internet Protocol Version 4, Src: " + srcIp + ", Des: " + desIp;
        QTreeWidgetItem* ipItem = new QTreeWidgetItem(QStringList() << tree);
        ui->treeWidget->addTopLevelItem(ipItem);

        QString ipProtocol = data.getIpProtocol();
        QList<QTreeWidgetItem *> ipItems = data.getIp();
        for(auto &childIpItem : ipItems) {
            ipItem->addChild(childIpItem);
        }

        if (ipProtocol == "TCP(6)")
        {
            QString sPort = data.getTcpSrcPort();
            QString dPort = data.getTcpDesPort();
            tree = "Transmission Control Protocol, Src Port: " + sPort + ", Dst Port: " + dPort;
            QTreeWidgetItem* tcpItem = new QTreeWidgetItem(QStringList() << tree);
            ui->treeWidget->addTopLevelItem(tcpItem);

            QString seqNum = data.getTcpSeq();
            QString ackNum = data.getTcpAck();
            tcpItem->addChild(new QTreeWidgetItem(QStringList() << "Sequence Number: " + seqNum));
            tcpItem->addChild(new QTreeWidgetItem(QStringList() << "Acknowledgment Number: " + ackNum));
        }
        else if (ipProtocol == "UDP(17)")
        {
            QString sPort = data.getUdpSrcPort();
            QString dPort = data.getUdpDesPort();
            QString length = data.getUdpLength();
            tree = "User Datagram Protocol, Src Port: " + sPort + ", Dst Port: " + dPort + ", Length: " + length;
            QTreeWidgetItem* udpItem = new QTreeWidgetItem(QStringList() << tree);
            ui->treeWidget->addTopLevelItem(udpItem);

            udpItem->addChild(new QTreeWidgetItem(QStringList() << "Source Port: " + sPort));
            udpItem->addChild(new QTreeWidgetItem(QStringList() << "Destination Port: " + dPort));
            udpItem->addChild(new QTreeWidgetItem(QStringList() << "Length: " + length));

            // 如果源端口或目标端口为53，表示DNS协议
            if (sPort == "53" || dPort == "53")
            {
                QString qr = data.getDnsFlagsQR();
                tree = "Domain Name System";
                tree += (qr == "0 Message is a query") ? " (query)" : " (response)";
                QTreeWidgetItem* dnsItem = new QTreeWidgetItem(QStringList() << tree);
                ui->treeWidget->addTopLevelItem(dnsItem);

                QList<QTreeWidgetItem *> dnsItems = data.getDns();
                for(auto &childDnsItem : dnsItems) {
                    dnsItem->addChild(childDnsItem);
                }
            }
        }
        else if (ipProtocol == "ICMP(1)")
        {
            tree = "Internet Control Message Protocol";
            QTreeWidgetItem* icmpItem = new QTreeWidgetItem(QStringList() << tree);
            ui->treeWidget->addTopLevelItem(icmpItem);

            QList<QTreeWidgetItem *> icmpItems = data.getIcmp();
            for(auto &childIcmpItem : icmpItems) {
                icmpItem->addChild(childIcmpItem);
            }
        }
    }
    else if (macType == "ARP(0x0806)")
    {
        QString Op = data.getArpOp();
        if (Op == "request(1)")
        {
            tree = "Address Resolution Protocol (request)";
        }
        else if (Op == "reply(2)")
        {
            tree = "Address Resolution Protocol (reply)";
        }
        else
        {
            tree = "Address Resolution Protocol";
        }
        QTreeWidgetItem* arpItem = new QTreeWidgetItem(QStringList() << tree);
        ui->treeWidget->addTopLevelItem(arpItem);

        QList<QTreeWidgetItem *> arpItems = data.getArp();
        for(auto &childArpItem : arpItems) {
            arpItem->addChild(childArpItem);
        }
    }
}

void Sniffer::on_searchSrcIP_textChanged(const QString &text)
{
    filterSrcIP = text.trimmed();
    applyFilters();
}

void Sniffer::on_searchDstIP_textChanged(const QString &text)
{
    filterDstIP = text.trimmed();
    applyFilters();
}

void Sniffer::applyFilters()
{
    showData.clear();

    for (auto &data : pData)
    {
        bool matchSrc = true;
        bool matchDst = true;

        if (!filterSrcIP.isEmpty())
        {
            matchSrc = data.getSource().contains(filterSrcIP);
        }

        if (!filterDstIP.isEmpty())
        {
            matchDst = data.getDestination().contains(filterDstIP);
        }

        if (matchSrc && matchDst)
        {
            showData.append(data);
        }
    }

    // 更新表格显示
    ui->tableWidget->setRowCount(showData.size());

    for (int i = 0; i < showData.size(); ++i)
    {
        DataPackage &data = showData[i];
        // 设置每行的数据，根据您的实际列数和内容进行调整
        ui->tableWidget->setItem(i, 0, new QTableWidgetItem(QString::number(i + 1)));
        ui->tableWidget->setItem(i, 1, new QTableWidgetItem(data.getTimeStmp()));
        ui->tableWidget->setItem(i, 2, new QTableWidgetItem(data.getSource()));
        ui->tableWidget->setItem(i, 3, new QTableWidgetItem(data.getDestination()));
        ui->tableWidget->setItem(i, 4, new QTableWidgetItem(data.getPackageType()));
        ui->tableWidget->setItem(i, 5, new QTableWidgetItem(data.getDataLength()));
        ui->tableWidget->setItem(i, 6, new QTableWidgetItem(data.getInfo()));
    }
}


